<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 检查token
$submittedToken = $_POST['form_token'] ?? '';
if (empty($submittedToken) || !isset($_SESSION['form_tokens']) || !in_array($submittedToken, $_SESSION['form_tokens'])) {
    echo json_encode(['success' => false, 'message' => '表单令牌无效，请刷新页面后重试']);
    exit;
}

// 移除已使用的token
$_SESSION['form_tokens'] = array_diff($_SESSION['form_tokens'], [$submittedToken]);

$action = $_POST['action'] ?? '';
$settlementId = intval($_POST['settlement_id'] ?? 0);
$settlementInfo = $_POST['settlement_info'] ?? '';

if ($settlementId <= 0) {
    echo json_encode(['success' => false, 'message' => '结算记录ID无效']);
    exit;
}

if ($action !== 'update_settlement_info') {
    echo json_encode(['success' => false, 'message' => '操作类型无效']);
    exit;
}

$db = getDB();

// 获取当前结算信息
$stmt = $db->prepare("SELECT settlement_screenshots FROM settlements WHERE id = ?");
$stmt->execute([$settlementId]);
$currentSettlement = $stmt->fetch();

if (!$currentSettlement) {
    echo json_encode(['success' => false, 'message' => '结算记录不存在']);
    exit;
}

// 处理现有截图
$currentScreenshots = [];
if (!empty($currentSettlement['settlement_screenshots'])) {
    $screenshots = json_decode($currentSettlement['settlement_screenshots'], true);
    if (is_array($screenshots) && !empty($screenshots)) {
        $currentScreenshots = $screenshots;
    }
}

// 处理新上传的截图
$newScreenshots = [];
if (isset($_FILES['settlement_screenshots']) && is_array($_FILES['settlement_screenshots']['name'])) {
    foreach ($_FILES['settlement_screenshots']['name'] as $key => $name) {
        if ($_FILES['settlement_screenshots']['error'][$key] === UPLOAD_ERR_OK) {
            $file = [
                'name' => $name,
                'type' => $_FILES['settlement_screenshots']['type'][$key],
                'tmp_name' => $_FILES['settlement_screenshots']['tmp_name'][$key],
                'error' => $_FILES['settlement_screenshots']['error'][$key],
                'size' => $_FILES['settlement_screenshots']['size'][$key]
            ];
            
            $uploadResult = uploadFile($file, 'settlement_screenshot');
            if ($uploadResult['success']) {
                $newScreenshots[] = $uploadResult['filename'];
            }
        }
    }
}

// 合并截图
$allScreenshots = array_merge($currentScreenshots, $newScreenshots);

// 更新结算信息
$stmt = $db->prepare("UPDATE settlements SET settlement_info = ?, settlement_screenshots = ?, updated_at = NOW() WHERE id = ?");
if ($stmt->execute([$settlementInfo, json_encode($allScreenshots), $settlementId])) {
    echo json_encode(['success' => true, 'message' => '结算信息更新成功']);
} else {
    echo json_encode(['success' => false, 'message' => '结算信息更新失败']);
}
?>